package com.hrw.musicplayer.activity;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.View.OnTouchListener;
import android.widget.ImageButton;
import android.widget.Toast;

import com.hrw.musicplayer.R;
import com.hrw.musicplayer.adapter.DirectoryAdapter;
import com.hrw.musicplayer.db.DataBaseProvider;
import com.hrw.musicplayer.db.FileTable;
import com.hrw.musicplayer.utils.Constants;

public class DirectoryActivity extends ListActivity {
	private ImageButton back_btn;
	private File[] files;
	private List<String> items = new ArrayList<String>();
	private String current_file_path = "";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.directory_list_activity);
		init();
	}

	private void init() {
		back_btn = (ImageButton) findViewById(R.id.back_btn);
		back_btn.setOnTouchListener(backListener);
		files = getDirectoryList(null);
		renderItems(files);
	}

	OnTouchListener backListener = new OnTouchListener() {
		@Override
		public boolean onTouch(View v, MotionEvent event) {
			if (event.getAction() == MotionEvent.ACTION_DOWN) {
				back_btn.setImageResource(R.drawable.back_pressed);
			} else if (event.getAction() == MotionEvent.ACTION_UP) {
				back_btn.setImageResource(R.drawable.back);
				finish();
			}
			return false;
		}

	};

	protected void onListItemClick(android.widget.ListView l, View v,
			int position, long id) {
		File file = null;
		if (position == 0) {
			file = new File(current_file_path);
			if (null != file) {
				String parentPath = file.getParent();
				if (null != parentPath
						&& !parentPath.equals(R.string.root_directory)) {
					current_file_path = parentPath;
					file = new File(current_file_path);
				}
			}

			files = getDirectoryList(file);
			renderItems(files);
		} else {
			if (items.get(position).indexOf(".mp3") == -1) {
				current_file_path = items.get(position);
			}
			file = new File(items.get(position));
			if (file.isDirectory()) {// directory
				files = getDirectoryList(file);
				renderItems(files);
			} else {// files
				Intent intent = this.getIntent();
				// intent.putExtra("filePath", file);
				this.setResult(Constants.DIRECTORY_TO_MAIN_RESULT_CODE, intent);
				showDialog("加入播放列表?", file);
			}
		}
	};

	private File[] getDirectoryList(File file) {
		File[] directoryList = null;
		if (null == file) {
			directoryList = new File("/").listFiles();
		} else {
			directoryList = file.listFiles();
		}
		return directoryList;
	}

	private void renderItems(File[] files) {
		if (null != files) {
			items.clear();
			items.add(getString(R.string.root_directory));
			for (File file : files) {
				if (file.isDirectory()) {
					if (file.getPath().indexOf("/sdcard") != -1
							|| file.getPath().indexOf("/system") != -1) {
						items.add(file.getPath());
					}
				}
				if (file.getPath().indexOf(".mp3") != -1) {
					items.add(file.getPath());
				}
			}
			setListAdapter(new DirectoryAdapter(this, items));
		}
	}

	private void showDialog(String msg, final File file) {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage(msg).setCancelable(false).setPositiveButton("确定",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						String fileName = file.getName().substring(0,
								file.getName().indexOf("."));
						if (query(fileName)) {
							insertMusic(file);// 添加音乐
							Intent intent = new Intent();
							setResult(
									Constants.CONFIRM_ADD_MUSIC_TO_MAIN_RESULT_CODE,
									intent);
							finish();
						}

					}
				}).setNegativeButton("取消", null);
		AlertDialog alert = builder.create();
		alert.show();

	}

	// 添加音乐到播放列表
	private final void insertMusic(File file) {

		ContentResolver cr = getContentResolver();
		ContentValues values = new ContentValues();
		Uri uri = DataBaseProvider.CONTENT_URI;
		String fileName = file.getName().substring(0,
				file.getName().indexOf("."));
		values.put(FileTable.NAME, fileName);
		values.put(FileTable.PATH, file.getAbsolutePath());
		cr.insert(uri, values);
		Toast.makeText(this, "已加入", Toast.LENGTH_LONG).show();
		// Intent intent = new Intent(FileExplorerActivity.this,
		// PlayListActivity.class);
		// startActivity(intent);
	}

	private boolean query(String name) {
		ContentResolver cr = getContentResolver();
		Uri uri = DataBaseProvider.CONTENT_URI;
		String[] projection = { FileTable.NAME };
		Cursor c = cr.query(uri, projection, null, null, null);
		if (c.moveToFirst()) {
			for (int i = 0; i < c.getCount(); i++) {
				c.moveToPosition(i);
				String fileName = c.getString(0);
				if (name.equals(fileName)) {// 判断播放列表中是否存在该歌曲
					AlertDialog.Builder builder = new AlertDialog.Builder(this);
					builder.setMessage("文件已存在").setCancelable(false)
							.setPositiveButton("返回列表",
									new DialogInterface.OnClickListener() {
										public void onClick(
												DialogInterface dialog, int id) {
											finish();
										}
									}).setNegativeButton("重新添加", null);
					AlertDialog alert = builder.create();
					alert.show();
					return false;
				}

			}
		}
		c.close();
		return true;
	}
}
